import { Component, OnInit } from '@angular/core'
import { ModalService } from '@shared/services/modal.service'
import { DataService } from '@shared/services/data.service'
import { DashboardService } from 'app/routes/dashboard/dashboard.abstract.service'
import { IAuditProcessReq } from '@shared/interfaces/audit'
import { NzMessageService } from 'ng-zorro-antd'
import { Router, ActivatedRoute } from '@angular/router'
import { I18NService } from '@core'

@Component({
  selector: 'app-audit-operate',
  templateUrl: './audit-operate.component.html',
})
export class AuditOperateComponent implements OnInit {
  reason: string

  constructor(
    private modalService: ModalService,
    private auditService: DashboardService,
    private dataService: DataService,
    private msg: NzMessageService,
    private router: Router,
    private route: ActivatedRoute,
    private i18n: I18NService
  ) {}

  ngOnInit() {}

  cancel(): void {
    this.router.navigate(['..'], { relativeTo: this.route })
  }

  reject(): void {
    this.modalService.warm(
      this.trans('GENERAL.NOTIFICATION.AUDIT_REJECT_CONFIRM'), this.trans('GENERAL.INFO.PROMPT')).subscribe(result => {
      if (!result) return
      const data = this.getData()
      this.sendRejectReq(data)
    })
  }

  approve(): void {
    this.modalService.warm(
      this.trans('GENERAL.NOTIFICATION.AUDIT_APPROVE_CONFIRM'), this.trans('GENERAL.INFO.PROMPT')).subscribe(result => {
      if (!result) return
      const data = this.getData()
      this.sendApproveReq(data)
    })
  }

  private getData(): IAuditProcessReq {
    const { jobID } = this.dataService.task
    return {
      jobs: [jobID],
      reason: this.reason,
    }
  }

  private sendRejectReq(data: IAuditProcessReq): void {
    this.auditService.reject(data).subscribe(this.handleSuccess.bind(this), this.handleError)
  }

  private sendApproveReq(data: IAuditProcessReq): void {
    this.auditService.resolve(data).subscribe(this.handleSuccess.bind(this), this.handleError)
  }

  private handleSuccess(result: boolean): void {
    this.router.navigateByUrl('dashboard/tasks/done')
  }

  private handleError(err): void {
    const { error } = err
    this.msg.error(this.trans('GENERAL.INFO.ERROR') + `: ${error.msg}`)
  }

  private trans(str: string, params?: Object): string {
    return this.i18n.fanyi(str, params)
  }
}
